var _7_backgroudColors = 
[
    '#f44336',
    '#e91e63',
    '#9c27b0',
    '#673ab7',
    '#3f51b5',
    '#2196F3',
    '#87CEEB',
    '#00bcd4',
    '#00ffff',
    '#009688',
    '#4CAF50',
    '#8bc34a',
    '#cddc39',
    '#fdf5e6',
    '#f0e68c',
    '#ffeb3b',
    '#ffc107'
];


function randomColorFactor() {
    return Math.round(Math.random() * 255);
};

function randomColor() {
    return 'rgba(' + randomColorFactor() + ',' + randomColorFactor() + ',' + randomColorFactor() + ',.7)';
}; 

function randomScalingFactor() {
    return (Math.random() > 0.5 ? 1.0 : -1.0) * Math.round(Math.random() * 100);
}

function getBarChartSampleData() {
    var backgroundColors = [randomColor(),randomColor(),randomColor(),randomColor()];
    return {
        labels: ["January", "February", "March", "April"],
        datasets: [{
            label: 'Dataset 1',
            backgroundColor: [
                _7_backgroudColors[0],
                _7_backgroudColors[1],
                _7_backgroudColors[2],
                _7_backgroudColors[3]
            ],
            data: [12, 0, 50, 25]
        }
        ]
    };
}

var defaultBarChartOptions = 
{
    // Elements options apply to all of the options unless overridden in a dataset
    // In this case, we are setting the border of each bar to be 2px wide and green
    elements: 
    {
        rectangle: 
        {
            borderWidth: 1,
            //borderColor: 'rgb(0, 255, 0)'
            //borderSkipped: 'bottom'
        }
    },
    responsive: true,
    legend: 
    {
        position: 'bottom',
    },
    title: 
    {
        display: true,
        text: '监控大图'
    },

    barPercentage: 0.5,
    categoryPercentage: 0.2,
    scales: {
        xAxes : 
        [ 
            {
                gridLines : {
                    display : false
                }
            } 
        ],
        yAxes: 
        [
            {
                display: true,
                ticks: 
                {
                    suggestedMin: 0, 
                    suggestedMax: 100,   // minimum will be 0, unless there is a lower value.
                    // OR //
                    stepSize: 5,
                    beginAtZero: true   // minimum value will be 0.
                }
            }
        ]
    }
};

var defaultLineChartOptions = 
{
    tooltips: 
    { mode: 'x-axis'},
    scales: 
    {   
        xAxes : 
        [ 
            {
                gridLines : 
                {
                    display : false
                }
            }
        ],
        yAxes: 
        [
            {
                display: true,
                scaleLabel: {
                    display: false,
                    labelString: 'Value'
                },
                ticks: {
                    suggestedMin: 0,
                    stepSize: 5,
                    suggestedMax: 50,
                }
            }
        ]
    }       
};

var intervalTime = 3000; //  time repeat
// init all data

// url is a http url, hander is a function,with a result
function callAsynWithHandler(url,handler) {
    $.ajax(
        {
            timeout: intervalTime,
            url: url,
            success: handler,
            error: function(xhr,status,error) {
                console.log("url:"+url);
                console.log("xhr:"+xhr);
                console.log("status:"+status);
                console.log("error:"+error);
            }
        }
    );
}

// init data 
function initData(url1,url2,url3,url4,filter){
    callAsynWithHandler(url1,function (result1) { 
        window.mServiceno = result1;
        callAsynWithHandler(url2,function (result2) {
            window.mLiveData = result2;
            callAsynWithHandler(url3,function (result3) {
                window.mReportData = result3;
                callAsynWithHandler(url4,function(result4){
                    window.mFilter = result4;
                    hiddenCustomeInfo();
                    refreshData();
                })
            })
        })
    });
}

function hiddenCustomeInfo() {
    $("div#collapseOne>div>div").each(function(){
        $(this).hide();
    });
    $("div#collapseTwo>div>div").each(function(){
        $(this).hide();
    });
    if(window.mFilter) {
        for (var i = 0; i < window.mFilter.length; i++) {
            $("div#collapseOne>div [data-id=\'"+window.mFilter[i]+"\']").show();
            $("div#collapseTwo>div [data-id=\'"+window.mFilter[i]+"\']").show();
        }
    }
    
}

// 更新条件过滤条件
function filterData() {
    var no;
    if(window.mCurNo && window.mCurNo != "全部") {
        no = mCurNo;
        $("#current_select_no").text(no);
    }else {
        no = 'all';
        $("#current_select_no").text("全部");
    }
    getLivedata(no);
    getReportData(no);
    getTimerDatas(no);
}

function getLivedata(key) {
        var data  = window.mLiveData["data"][key];
        setData(data,"div#key_data ul#live_data span")
        setData(data,"div#collapseOne>div",'div.post-featured-image');
        setChartLiveData(data,key);
}

function getReportData(key) {
        var data = window.mReportData["data"][key]["statData"];
        setData(data,"div#collapseTwo>div","div.post-featured-image");
        setData(data,"div#key_data ul#report_data span")
}

function getTimerDatas(key) {
            var ctxLine = document.getElementById("line").getContext("2d");
            var timeRanges = window.mTimerData["timeRanges"]; //array
            var dataArrays = window.mTimerData["data"];// array;

            var inboundNums = {};//呼入量
            var acdCallsNums = {};//转人工量
            var ansAcdCallNums = {}; // 人工接通量
            var outboundNums = {};// 呼出量 
            var maxTime = timeRanges[0]; 

            for (var index in dataArrays){
                if (dataArrays[index]['timeRange'] > maxTime) {
                    maxTime = dataArrays[index]['timeRange'];
                }
            }

            var maxIndex = $.inArray(maxTime,timeRanges) + 1;
            // then filter the data 
            for(var i = 0; i < dataArrays.length;i++){
                var item = dataArrays[i];
                if(item["serviceNo"] == key){
                    var timeRangeItem = item["timeRange"];
                    if(timeRangeItem && timeRangeItem != ""){
                        inboundNums[timeRangeItem] = item["inboundNum"];
                        acdCallsNums[timeRangeItem] = item["acdCallsNum"];
                        ansAcdCallNums[timeRangeItem] = item["ansAcdCallNum"];
                        outboundNums[timeRangeItem] = item["outboundNum"];
                    }
                }
            }
            
            var data = {
                labels: timeRanges,
                datasets:[
                    {
                        label:"呼入量",
                        fill: false,
                        lineTension: 0.1,
                        borderWidth: 3,
                        borderColor: "rgba(220,20,60,1)",
                        backgroundColor: "rgba(220,20,60,1)",
                        data:formatTimerDatas(timeRanges,inboundNums)
                    },
                    {
                        label:"呼出量",
                        fill: false,
                        lineTension: 0.1,
                        borderWidth: 3,
                        borderColor: "rgba(139,0,139,1)",
                        backgroundColor: "rgba(139,0,139,1)",
                        data:formatTimerDatas(timeRanges,outboundNums)
                    },
                    {
                        label:"转人工量",
                        fill: false,
                        lineTension: 0.1,
                        borderWidth: 3,
                        borderColor: "rgba(72,61,139,1)",
                        backgroundColor: "rgba(72,61,139,1)",
                        data:formatTimerDatas(timeRanges,acdCallsNums)
                    },
                    {
                        label:"人工接通量",
                        fill: false,
                        lineTension: 0.1,
                        borderWidth: 3,
                        borderColor: "rgba(65,105,225,1)",
                        backgroundColor: "rgba(65,105,225,1)",
                        data:formatTimerDatas(timeRanges,ansAcdCallNums)
                    }
                ]
            };

            var options = {

                tooltips: {
                    mode: 'x-axis'
                },
                scales: {
                    xAxes : [ {
                        gridLines : {
                            display : false
                        }
                    } ],
                            yAxes: [{
                                display: true,
                                scaleLabel: {
                                    display: false,
                                    labelString: 'Value'
                                },
                                ticks: {
                                    suggestedMin: 0,
                                    stepSize: 5,
                                    suggestedMax: 50,
                                }
                                }]
                        }
            };

            if(window.myLine) {
                window.myLine.data = data;
                window.myLine.update();
            }else {
                window.myLine = new Chart(ctxLine, {
                        type: 'line',
                        data: data,
                        options: options
                    });
            }
}

function formatTimerDatas(key,map){
        var ar = new Array();
        for (var i = 0 ; i< key.length;i++){
            var value = map[key[i]];
            ar[i] = value;
        }
        return ar;
}

// 定时请求数据
function repeatRequest() {
    // setTimeout(function(){
    //     $.ajax({timeout: intervalTime, url: http1,success: function(result){
    //         window.mLiveData = result;
    //         filterData();
    //         repeatRequest();
    //     }});
    // },intervalTime);
        setInterval(function(){
        $.ajax({timeout:intervalTime,url: http1,success: function(result){
            console.log("success:"+result);
            window.mLiveData = result;
            filterData();
        },error:function(xhr,status,error){
            console.log("error:"+error);
        }})
        },intervalTime);
}


function setChartLiveData(data,key){
             var labelsAndKey = [
                 ["AgentTotal","签入人数"],
                 ["AgentAfterCallWork","整理人数"],
                 ["AgentNotReady","置忙人数"],
                 ["AgentOtherWork","休息人数"],
                 ["AgentReady","空闲人数"],
                 ["AgentTalking","通话人数"],
                 ["AgentOtherstatus","其他人数"],
            ];

             var charData = [
                        data[labelsAndKey[0][0]], 
                        data[labelsAndKey[1][0]], 
                        data[labelsAndKey[2][0]], 
                        data[labelsAndKey[3][0]], 
                        data[labelsAndKey[4][0]], 
                        data[labelsAndKey[5][0]], 
                        data[labelsAndKey[6][0]]
                    ];

             var dataChart = {
                 labels: [labelsAndKey[0][1],labelsAndKey[1][1],labelsAndKey[2][1],labelsAndKey[3][1],labelsAndKey[4][1],labelsAndKey[5][1],labelsAndKey[6][1]],
                 datasets: [{
                    label: '监控',
                    backgroundColor: [_7_backgroudColors[0],
                                    _7_backgroudColors[1],
                                    _7_backgroudColors[2],
                                    _7_backgroudColors[3],_7_backgroudColors[4],
                _7_backgroudColors[5],
                _7_backgroudColors[6],
                    ],
                    data: charData
                }]
            } 

            var ctxBar = document.getElementById("bar").getContext("2d");
            if(window.myBar){
                window.myBar.data.datasets[0].data = charData;
                window.myBar.update();
            }else {
                window.myBar = new Chart(ctxBar, {
                    type: 'bar',
                    data: dataChart,
                    options: {
                        // Elements options apply to all of the options unless overridden in a dataset
                        // In this case, we are setting the border of each bar to be 2px wide and green
                        elements: {
                            rectangle: {
                                borderWidth: 1,
                                //borderColor: 'rgb(0, 255, 0)'
                                //borderSkipped: 'bottom'
                         }
                        },
                        responsive: true,
                        legend: {
                            display:false,
                            position: 'top',
                        },
                        title: {
                            display: true,
                            text: '监控大图'
                        },
                        scales: {
                            xAxes : [ {
                                gridLines : {
                                    display : false
                                }
                            } ],
                            yAxes: [{
                                display: true,
                                ticks: {
                                    suggestedMin: 0,    // minimum will be 0, unless there is a lower value.
                                    // OR //
                                    stepSize: 1,
                                    beginAtZero: true   // minimum value will be 0.
                                }
                            }]
                        }
                    }
                });
            }
}

function setData(data,selector,numSelector) {
    $(selector).each(function(){
        var item = $(this);
        var key = item.data("id");
        var unit = item.data("unit");
        var value = data[key];
        var $html;
        if (numSelector) {
            $html = item.find(numSelector);
        }else {
            $html = item;
        }
        if(value == "" || value === undefined ) {
            value = "0";
        }
        if(unit){
            $html.text(value+unit);
        }else {
            $html.text(value);
        }
    });
}

// 首次获取数据刷新页面
function refreshData() {
    $("#line_number li").remove();
    $("#line_number").append("<li><a href=\"#\">全部</a></li>");
    window.mServiceno.forEach(function(item){
        var newli = "<li><a href=\"#\">"+ item +"</a></li>"
        $("#line_number").append(newli);
        $("#line_number > li").unbind("click").click(function(e){
                window.mCurNo = $(this).text();
                filterData(window.mCurNo);
                if ($(".navbar-collapse").hasClass('in')){
                    $("#navbar").collapse('toggle');
                }
                e.preventDefault();
        });
    });
    filterData();
    repeatRequest();
}


// Cookies
function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";               

    document.cookie = name + "=" + value + expires + "; path=/";
}
// to read userId use "readCookie("userId")"
function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}